<template>
  <div class="layout-container">
    <!-- 左侧导航栏 -->
    <aside class="sidebar" :class="{ 'collapsed': isSidebarCollapsed }">
      <!-- 产品Logo和名称 -->
      <div class="logo-container">
        <img src="../assets/OIP-C.jpg" alt="Logo" class="logo"/>
        <h1 class="app-name" v-if="!isSidebarCollapsed">AI Assistant</h1>
      </div>

      <!-- 新建对话按钮 -->
      <button class="new-chat-btn" @click="createNewChat">
        <font-awesome-icon :icon="['fas', 'plus']"/>
        <span v-if="!isSidebarCollapsed">新建对话</span>
      </button>

      <!-- 导航菜单区域 -->
      <nav class="nav-menu">
        <!-- 历史对话列表 -->
        <div class="menu-section">
          <div class="section-header" v-if="!isSidebarCollapsed">
            <span>历史对话</span>
          </div>

          <ul class="conversation-list">
            <li v-for="(chat, index) in chatHistory" :key="chat.id" :class="{ 'active': currentChatId === chat.id }"
                @click="selectChat(chat.id)">
              <div class="chat-content">
                <font-awesome-icon :icon="['fas', 'message']"/>
                <span class="chat-title" v-if="!isSidebarCollapsed">{{ chat.title }}</span>
              </div>
              <div class="chat-actions" v-if="!isSidebarCollapsed" @click.stop>
                <button class="action-icon edit-icon" @click="startEditChat(chat)" title="修改名称">
                  <font-awesome-icon :icon="['fas', 'pen']"/>
                </button>
                <button class="action-icon delete-icon" @click="deleteChat(chat.id)" title="删除对话">
                  <font-awesome-icon :icon="['fas', 'trash']"/>
                </button>
              </div>
            </li>
          </ul>
        </div>
      </nav>

      <!-- 底部设置区域 -->
      <div class="sidebar-footer">
        <div class="user-info" v-if="!isSidebarCollapsed">
          <img :src="userAvatar" alt="User Avatar" class="avatar"/>
          <span class="username">{{ username }}</span>
        </div>

        <div class="settings-buttons">
          <button class="settings-btn" @click="openSettings" title="设置">
            <font-awesome-icon :icon="['fas', 'gear']"/>
            <span v-if="!isSidebarCollapsed">设置</span>
          </button>
        </div>

        <!-- 侧边栏折叠按钮 -->
        <button class="collapse-btn" @click="toggleSidebar" :title="isSidebarCollapsed ? '展开侧边栏' : '折叠侧边栏'">
          <font-awesome-icon :icon="['fas', isSidebarCollapsed ? 'angle-right' : 'angle-left']"/>
        </button>
      </div>
    </aside>

    <!-- 主内容区域 -->
    <main class="main-content">
      <!-- 顶部导航栏 -->
      <header class="top-navbar">
        <div class="chat-title">
          <h2>{{ currentChat ? currentChat.title : '新对话' }}</h2>
        </div>

        <div class="action-buttons">
          <button class="action-btn" @click="searchInChat" title="搜索">
            <font-awesome-icon :icon="['fas', 'search']"/>
          </button>
          <button class="action-btn" @click="shareChat" title="分享">
            <font-awesome-icon :icon="['fas', 'share-nodes']"/>
          </button>
          <button class="action-btn" @click="chatSettings" title="聊天设置">
            <font-awesome-icon :icon="['fas', 'ellipsis-vertical']"/>
          </button>
        </div>
      </header>

      <!-- 聊天内容区域 - 直接使用Chat组件 -->
      <div class="chat-container">
        <router-view></router-view>
      </div>
    </main>

    <!-- 编辑对话名称的弹窗 -->
    <div class="edit-dialog" v-if="showEditDialog" @click.self="cancelEditChat" @keydown.esc="cancelEditChat">
      <div class="edit-dialog-content">
        <div class="dialog-header">
          <h3>修改对话名称</h3>
          <button class="close-btn" @click="cancelEditChat" title="关闭">
            <font-awesome-icon :icon="['fas', 'times']"/>
          </button>
        </div>
        <input type="text" v-model="editingChatTitle" class="edit-input" ref="editInput" @keyup.enter="saveEditChat"
               placeholder="请输入对话名称" maxlength="50">
        <div class="dialog-buttons">
          <button @click="cancelEditChat" class="cancel-btn">取消</button>
          <button @click="saveEditChat" class="save-btn" :disabled="!editingChatTitle.trim()">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, computed, nextTick, watch, provide, onMounted} from 'vue';
import {getChatConversations, updateChatConversation} from '../apis/conversation';
import {deleteAllMessages} from '../apis/messages';

// 侧边栏状态
const isSidebarCollapsed = ref(false);

// 用户信息
const username = ref('白开水不加冰');
const userAvatar = ref('src/assets/头像.jpg');

// 聊天数据
const currentChatId = ref(null);
const chatHistory = ref([]);

// 加载会话历史
const loadChatHistory = async () => {
  try {
    const res = await getChatConversations();
    if (res.code === 0 && res.data) {
      // 将后端返回的chatId映射为前端使用的id
      chatHistory.value = res.data.map(chat => ({
        id: chat.chatId.toString(),
        title: chat.title
      }));
    }
  } catch (error) {
    console.error('加载会话历史失败:', error);
  }
};

// 组件挂载时加载会话历史
onMounted(() => {
  loadChatHistory();
});

// 对话编辑相关
const showEditDialog = ref(false);
const editingChatId = ref(null);
const editingChatTitle = ref('');
const editInput = ref(null);

// 新建对话事件
const newChatRequested = ref(false);

// 选中对话的ID
const selectedChatId = ref(null);

// 清除对话内容事件
const clearChatContent = ref(false);

// 向子组件提供通信所需的数据
provide('newChatRequested', newChatRequested);
provide('selectedChatId', selectedChatId);
provide('clearChatContent', clearChatContent);

// 当前选中的聊天
const currentChat = computed(() => {
  // 从历史中查找
  const fromHistory = chatHistory.value.find(chat => chat.id === currentChatId.value);
  if (fromHistory) return fromHistory;

  return null;
});

// 方法
const toggleSidebar = () => {
  isSidebarCollapsed.value = !isSidebarCollapsed.value;
};

const createNewChat = () => {
  // 只清除当前的memoryId来创建新对话
  localStorage.removeItem('memoryId');
  localStorage.removeItem('flg');

  // 清除选中状态，表示进入新对话
  currentChatId.value = null;
  selectedChatId.value = null;

  // 通知聊天组件创建新对话
  newChatRequested.value = !newChatRequested.value;

  // 重新加载会话列表，确保显示包括新创建的会话
  setTimeout(() => {
    loadChatHistory();
  }, 500);
};

const selectChat = (chatId) => {
  currentChatId.value = chatId;
  // 设置选中的聊天ID，通知Chat组件加载对应聊天记录
  selectedChatId.value = chatId;
  
  // 确保在选择会话时设置localStorage
  localStorage.setItem('memoryId', chatId);
  localStorage.setItem('flg', 'true');
};

// 编辑对话名称
const startEditChat = (chat) => {
  editingChatId.value = chat.id;
  editingChatTitle.value = chat.title;
  showEditDialog.value = true;

  // 等待DOM更新后聚焦到输入框
  nextTick(() => {
    if (editInput.value) {
      editInput.value.focus();
      editInput.value.select(); // 全选文本，方便用户直接输入
    }
  });
};

const saveEditChat = async () => {
  if (editingChatTitle.value.trim()) {
    try {
      // 调用API更新会话标题
      const params = {
        chatId: editingChatId.value,
        title: editingChatTitle.value.trim()
      };

      const res = await updateChatConversation(params);

      if (res.code === 0) {
        // 更新本地数据
        const chatIndex = chatHistory.value.findIndex(chat => chat.id === editingChatId.value);
        if (chatIndex !== -1) {
          chatHistory.value[chatIndex].title = editingChatTitle.value.trim();
        }
      }
    } catch (error) {
      console.error('修改会话标题失败:', error);
    }
  }
  cancelEditChat();
};

const cancelEditChat = () => {
  showEditDialog.value = false;
  editingChatId.value = null;
  editingChatTitle.value = '';
};

// 删除对话
const deleteChat = async (chatId) => {
  if (confirm('确定要删除这个对话吗？')) {
    try {
      // 调用API删除会话
      const res = await deleteAllMessages(chatId);

      if (res.code === 0) {
        // 获取当前存储在localStorage中的memoryId
        const currentMemoryId = localStorage.getItem('memoryId');

        // 判断是否需要清除主页面内容（当删除的是当前选中的对话或当前显示的对话）
        const shouldClearContent = currentChatId.value === chatId || currentMemoryId === chatId;

        // 如果需要清除主页面，则清除localStorage和状态
        if (shouldClearContent) {
          localStorage.removeItem('memoryId');
          localStorage.removeItem('flg');

          // 如果是当前选中的对话，也清除选中状态
          if (currentChatId.value === chatId) {
            currentChatId.value = null;
            selectedChatId.value = null;
          }

          // 触发清除主页面内容的事件，通知聊天组件清除显示
          clearChatContent.value = !clearChatContent.value;
        }

        // 更新本地数据
        chatHistory.value = chatHistory.value.filter(chat => chat.id !== chatId);

        // 重新加载会话列表
        loadChatHistory();
      }
    } catch (error) {
      console.error('删除对话失败:', error);
    }
  }
};

const searchInChat = () => {
  // 搜索聊天内容
  console.log('搜索聊天内容');
};

const shareChat = () => {
  // 分享聊天
  console.log('分享聊天');
};

const chatSettings = () => {
  // 打开聊天设置
  console.log('聊天设置');
};

const openSettings = () => {
  // 打开系统设置
  console.log('打开系统设置');
};
</script>

<style scoped>
.layout-container {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

/* 左侧导航栏样式 */
.sidebar {
  width: 260px;
  height: 100%;
  background-color: #f5f5f5;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  transition: none;
}

.sidebar.collapsed {
  width: 60px;
}

/* Logo区域 */
.logo-container {
  display: flex;
  align-items: center;
  padding: 0 16px;
  height: 64px;
  border-bottom: 1px solid #e0e0e0;
  box-sizing: border-box;
}

.logo {
  width: 32px;
  height: 32px;
}

.app-name {
  margin-left: 10px;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

/* 新建对话按钮 */
.new-chat-btn {
  margin: 16px;
  padding: 10px 16px;
  background-color: #007bff;
  color: white;
  border-radius: 6px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  cursor: pointer;
  box-sizing: border-box;
  transition: none;
}

.new-chat-btn:hover {
  background-color: #0069d9;
}

/* 导航菜单区域 */
.nav-menu {
  flex: 1;
  overflow-y: auto;
  padding: 0 8px;
  position: relative;
}

.menu-section {
  margin-bottom: 24px;
  position: relative;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.group-btn {
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  padding: 4px;
}

.group-btn:hover {
  color: #333;
}

/* 对话列表样式 */
.conversation-list,
.group-list,
.favorite-list,
.group-chats {
  list-style: none;
  padding: 0;
  margin: 0;
}

.conversation-list li,
.group-list li,
.favorite-list li,
.group-chats li {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 12px;
  margin: 0 0 2px 0;
  cursor: pointer;
  position: relative;
  background-color: transparent;
  border: none;
  outline: none;
  border-radius: 0;
  transition: none;
}

.conversation-list li:hover,
.group-list li:hover,
.favorite-list li:hover,
.group-chats li:hover {
  background-color: #f0f0f0;
}

.conversation-list li.active,
.group-chats li.active,
.favorite-list li.active {
  background-color: #e2f0ff;
  color: #007bff;
  transition: none;
}

.chat-content {
  display: flex;
  align-items: center;
  flex: 1;
  overflow: hidden;
  min-width: 0;
}

.conversation-list .svg-inline--fa,
.group-list .svg-inline--fa,
.favorite-list .svg-inline--fa,
.group-chats .svg-inline--fa {
  margin-right: 10px;
  width: 16px;
  height: 16px;
  text-align: center;
  flex-shrink: 0;
}

.chat-title,
.group-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 14px;
  max-width: 100%;
  min-width: 0;
}

/* 分组子列表 */
.group-chats {
  margin-left: 15px;
  margin-top: 5px;
}

/* 底部设置区域 */
.sidebar-footer {
  padding: 16px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
}

.username {
  font-size: 14px;
  font-weight: 500;
}

.settings-buttons {
  display: flex;
  align-items: center;
  gap: 10px;
}

.settings-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 10px;
  background: none;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  color: #666;
  font-size: 14px;
  box-sizing: border-box;
}

.settings-btn:hover {
  background-color: #e9ecef;
}

.collapse-btn {
  margin-top: 10px;
  align-self: center;
  padding: 6px;
  background: none;
  border: 1px solid #e0e0e0;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  box-sizing: border-box;
}

/* 主内容区域样式 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #fff;
}

/* 顶部导航栏 */
.top-navbar {
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  border-bottom: 1px solid #e0e0e0;
  box-sizing: border-box;
}

.chat-title h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-btn {
  background: none;
  border: none;
  color: #666;
  padding: 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.action-btn:hover {
  background-color: #f5f5f5;
  color: #333;
}

/* 聊天内容区域 */
.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 10px 20px;
  background-color: #f9f9f9;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    z-index: 100;
    transform: translateX(-100%);
    box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
  }

  .sidebar.visible {
    transform: translateX(0);
  }

  .main-content {
    margin-left: 0;
  }
}

.chat-actions {
  display: none;
  margin-left: 8px;
  align-items: center;
  flex-shrink: 0;
  /* 防止按钮区域缩小 */
  gap: 4px;
}

.conversation-list li:hover .chat-actions {
  display: flex;
}

/* 完全重写操作按钮的样式 */
.action-icon {
  background: none;
  border: none;
  color: #666;
  width: 28px;
  height: 28px;
  display: inline-block;
  position: relative;
  cursor: pointer;
  border-radius: 4px;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  transition: none;
}

.action-icon:hover {
  color: #333;
  background-color: rgba(0, 0, 0, 0.08);
}

/* 确保图标大小一致 */
.action-icon .svg-inline--fa {
  width: 14px;
  height: 14px;
  font-size: 14px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.edit-icon .svg-inline--fa {
  font-size: 11px;
  width: 11px;
  height: 11px;
}

/* 编辑对话弹窗 */
.edit-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  backdrop-filter: blur(2px);
}

.edit-dialog-content {
  background-color: white;
  padding: 24px;
  border-radius: 12px;
  width: 350px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.close-btn {
  background: none;
  border: none;
  color: #888;
  font-size: 16px;
  cursor: pointer;
  padding: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  box-sizing: border-box;
  transition: none;
}

.close-btn:hover {
  background-color: #f0f0f0;
  color: #333;
}

.edit-dialog-content h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 500;
}

.edit-input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  margin-bottom: 24px;
  font-size: 14px;
  box-sizing: border-box;
}

.edit-input:focus {
  border-color: #007bff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.dialog-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.cancel-btn,
.save-btn {
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  box-sizing: border-box;
  transition: none;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #ddd;
}

.cancel-btn:hover {
  background-color: #e9e9e9;
}

.save-btn {
  background-color: #007bff;
  color: white;
  border: none;
}

.save-btn:hover {
  background-color: #0069d9;
}

.save-btn:disabled {
  background-color: #b3d7ff;
  cursor: not-allowed;
}
</style>